<template>
  <div class="app-container">
    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="auto">
      <el-form-item label="计划编号" prop="orderNo">
        <el-input v-model="queryParams.orderNo" placeholder="请输入计划编号" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="车间" prop="deptId">
        <treeselect style="width: 200px" v-model="queryParams.deptId" :options="deptList" :normalizer="normalizer"
                    placeholder="请选择车间" clearable/>
      </el-form-item>
      <el-form-item label="业务类型" prop="businessType">
        <el-select v-model="queryParams.businessType" filterable placeholder="请选择业务类型" clearable size="small">
          <el-option v-for="dict in this.getDictDatas(DICT_TYPE.ORDER_BUSINESS_TYPE)" :key="dict.value"
                     :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="openForm(undefined)"
                   v-hasPermi="['production:order:create']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                   :loading="exportLoading"
                   v-hasPermi="['production:order:export']">导出
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="danger"-->
      <!--          plain-->
      <!--          icon="el-icon-delete"-->
      <!--          size="mini"-->
      <!--          :disabled="isEmpty(checkedIds)"-->
      <!--          @click="handleDeleteBatch"-->
      <!--          v-hasPermi="['production:order:delete']"-->
      <!--        >-->
      <!--          批量删除-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      @selection-change="handleRowCheckboxChange"
    >
      <!-- <el-table-column type="selection" width="55" /> -->
      <el-table-column label="计划编号" align="center" prop="orderNo" show-overflow-tooltip min-width="200"/>
      <el-table-column label="单据日期" align="center" prop="billDate" min-width="150"/>
      <el-table-column label="车间" align="center" prop="deptName" min-width="150"/>
      <el-table-column label="业务类型" align="center" prop="businessType" min-width="100">
        <template v-slot="scope">
          <span>{{ getDictDataLabel(DICT_TYPE.ORDER_BUSINESS_TYPE, scope.row.businessType) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="车间编号" align="center" prop="deptCode" min-width="150"/>
      <el-table-column label="车间名称" align="center" prop="deptName" min-width="150"/>
      <el-table-column label="计划开始时间" align="center" prop="planBeginTime" min-width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.planBeginTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计划结束时间" align="center" prop="planEndTime" min-width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.planEndTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建者" align="center" prop="creator" width="150"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="200">
        <template v-slot="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="openForm(scope.row.id)"
                     v-hasPermi="['production:order:update']">修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['production:order:delete']">删除
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleDetail(scope.row)"
          >详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>
    <!-- 对话框(添加 / 修改) -->
    <OrderForm ref="formRef" @success="getList"/>

    <!-- 详情弹窗 -->
    <el-dialog title="订单详情" :visible.sync="detailDialogVisible" width="80%" append-to-body>
      <el-table :data="currentOrderItems" style="width: 100%" max-height="700px">
        <el-table-column label="产品类型" prop="productType" align="center"/>
        <el-table-column label="产品编码" prop="productCode" align="center"/>
        <el-table-column label="产品名称" prop="productName" align="center"/>
        <el-table-column label="数量" prop="quantity" align="center"/>
        <el-table-column label="产品BOM版本" prop="productBomVersion" align="center"/>
        <el-table-column label="业务状态" prop="businessStatus" align="center"/>
        <el-table-column label="领料状态" prop="pickingStatus" align="center"/>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as OrderApi from '@/api/production/order';
import OrderForm from './OrderForm.vue';
import {listDept} from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {getOrder} from "@/api/production/order";

export default {
  name: "Order",
  components: {
    OrderForm,
    Treeselect
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 生产订单列表
      list: [],
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 选中行
      currentRow: {},
      checkedIds: [],
      // 详情弹窗相关
      detailDialogVisible: false,
      currentOrderItems: [],
      // 部门列表
      deptList: [],
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        orderNo: null,
        billDate: [],
        deptId: null,
        businessType: null,
        deptCode: null,
        deptName: null,
        planBeginTime: [],
        planEndTime: [],
        createTime: [],
      },
    };
  },
  created() {
    this.getList();
    this.getDeptList();
  },
  methods: {
    /** 查询列表 */
    async getList() {
      try {
        this.loading = true;
        const res = await OrderApi.getOrderPage(this.queryParams);
        this.list = res.data.list;
        this.total = res.data.total;
      } finally {
        this.loading = false;
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 添加/修改操作 */
    openForm(id) {
      this.$refs["formRef"].open(id);
    },
    /** 删除按钮操作 */
    async handleDelete(row) {
      const id = row.id;
      await this.$modal.confirm('是否确认删除生产订单编号为"' + id + '"的数据项?')
      try {
        await OrderApi.deleteOrder(id);
        await this.getList();
        this.$modal.msgSuccess("删除成功");
      } catch {
      }
    },
    /** 批量删除生产订单 */
    async handleDeleteBatch() {
      await this.$modal.confirm('是否确认删除?')
      try {
        await OrderApi.deleteOrderList(this.checkedIds);
        this.checkedIds = [];
        await this.getList();
        this.$modal.msgSuccess("删除成功");
      } catch {
      }
    },
    handleRowCheckboxChange(records) {
      this.checkedIds = records.map((item) => item.id);
    },

    /** 详情按钮操作 */
    async handleDetail(row) {
      const res = await OrderApi.getOrder(row.id);
      console.log(res, 'czq')
      this.currentOrderItems = res.data.itemList || [];
      this.detailDialogVisible = true;
    },
    /** 导出按钮操作 */
    async handleExport() {
      await this.$modal.confirm('是否确认导出所有生产订单数据项?');
      try {
        this.exportLoading = true;
        const data = await OrderApi.exportOrderExcel(this.queryParams);
        this.$download.excel(data, '生产订单.xls');
      } catch {
      } finally {
        this.exportLoading = false;
      }
    },

    /** 获取部门列表 */
    getDeptList() {
      listDept().then(response => {
        this.deptList = this.handleTree(response.data, "id")[0]?.children || [];
      });
    },

    /** 处理树形数据 */
    handleTree(data, id, parentId, children, rootId) {
      id = id || 'id';
      parentId = parentId || 'parentId';
      children = children || 'children';
      rootId = rootId || Math.min.apply(Math, data.map(item => {
        return item[parentId] || 0
      })) || 0;
      // 对源数据深度克隆
      const cloneData = JSON.parse(JSON.stringify(data));
      // 循环所有项
      const treeData = cloneData.filter(father => {
        const branchArr = cloneData.filter(child => {
          // 返回每一项的子级数组
          return father[id] === child[parentId];
        });
        branchArr.length > 0 ? father[children] = branchArr : delete father[children];
        // 返回第一层
        return father[parentId] === rootId;
      });
      return treeData.length > 0 ? treeData : cloneData;
    },

    /** 部门节点格式化 */
    normalizer(node) {
      const normalizedNode = {
        id: node.id,
        label: node.name,
        children: node.children,
      };
      return normalizedNode;
    }
  }
};
</script>
